package com.atguigu.mall.product.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.mall.product.consts.Const;
import com.atguigu.mall.product.dao.CategoryDao;
import com.atguigu.mall.product.entity.CategoryEntity;
import com.atguigu.mall.product.service.CategoryBrandRelationService;
import com.atguigu.mall.product.service.CategoryService;
import com.atguigu.mall.product.vo.Catelog2Vo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Resource
    private CategoryBrandRelationService categoryBrandRelationService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree(String name,Integer isDisable) {
        LambdaQueryWrapper<CategoryEntity> wrapper = new LambdaQueryWrapper<CategoryEntity>();
        if (StrUtil.isNotBlank(name)){
            wrapper.like(CategoryEntity::getName,name);
        }
        List<CategoryEntity> list = this.list(wrapper);

        list.forEach(item->{
            Integer catLevel = item.getCatLevel();
            Boolean flag = !catLevel.equals(3) &&  isDisable.equals(Const.CATEGORY_DISABLE);
            item.setDisabled(flag);
        });

        List<CategoryEntity> rootList = list.stream().filter(item -> item.getParentCid().equals(Const.ROOT_FLAG)).collect(Collectors.toList());
        List<CategoryEntity> treeResult = rootList.stream()
                .map(item -> buildTree(item, list))
                .sorted(Comparator.comparing(CategoryEntity::getSort))
                .collect(Collectors.toList());
        return treeResult;
    }
    @Override
    public List<CategoryEntity> queryChildrenListById(Long categoryId) {
        LambdaQueryWrapper<CategoryEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CategoryEntity::getParentCid,categoryId);
        return this.baseMapper.selectList(wrapper);
    }
    @Override
    public List<Long> queryPathListById(Long categoryId) {
        List<Long> pathList = new ArrayList<>();
        findPath(categoryId, pathList);
        CollUtil.reverse(pathList);
        return pathList;
    }


    @CacheEvict(value = "category",allEntries = true)
    @Override
    public void updateByCategory(CategoryEntity category) {
        this.updateById(category);
        Long catId = category.getCatId();
        String categoryName = category.getName();
        categoryBrandRelationService.updateCategoryNameByCategoryId(catId,categoryName);
    }

    @Cacheable(value = "category",key = "#root.methodName")
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        log.info("getLevel1Categorys重新缓存");
        LambdaQueryWrapper<CategoryEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CategoryEntity::getParentCid,0L);
        wrapper.eq(CategoryEntity::getShowStatus,1);
        return  this.baseMapper.selectList(wrapper);
    }

    @Cacheable(value = "category",key = "#root.methodName")
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        return getCatalogJsonForDb();
    }


    public Map<String, List<Catelog2Vo>> getCatalogJsonForDb() {
        //将数据库的多次查询变为一次
        List<CategoryEntity> selectList = this.baseMapper.selectList(null);
        //1、查出所有分类
        //1、1）查出所有一级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
        //封装数据
        Map<String, List<Catelog2Vo>> parentCid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1、每一个的一级分类,查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());

            //2、封装上面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName().toString());

                    //1、找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());

                    if (level3Catelog != null) {
                        List<Catelog2Vo.Category3Vo> category3Vos = level3Catelog.stream().map(l3 -> {
                            //2、封装成指定格式
                            Catelog2Vo.Category3Vo category3Vo = new Catelog2Vo.Category3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                            return category3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(category3Vos);
                    }

                    return catelog2Vo;
                }).collect(Collectors.toList());
            }

            return catelog2Vos;
        }));
        return parentCid;
    }
    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList,Long parentCid) {
        List<CategoryEntity> categoryEntities = selectList.stream().filter(item -> item.getParentCid().equals(parentCid)).collect(Collectors.toList());
        return categoryEntities;
    }

    private List<Long> findPath(Long categoryId,List<Long> pathList){
        pathList.add(categoryId);
        CategoryEntity categoryEntity = this.getById(categoryId);
        Long parentCid = categoryEntity.getParentCid();
        if (!Const.ROOT_FLAG.equals(parentCid)){
            findPath(parentCid,pathList);
        }
        return  pathList;
    }


    private  static CategoryEntity buildTree(CategoryEntity root,List<CategoryEntity> all){
        Long catId = root.getCatId();
        List<CategoryEntity> childAll = all.stream()
                .filter(item -> item.getParentCid().equals(catId))
                .sorted(Comparator.comparing(CategoryEntity::getSort))
                .map(child -> buildTree(child, all))
                .collect(Collectors.toList());
        root.setChildren(childAll);
        return root;
    }



}